import axios from "axios";

// 直接在当前文件中获取平台信息（无需依赖env.js）
let platform = 'h5'; // 默认H5环境
try {
  const systemInfo = uni.getSystemInfoSync();
  platform = systemInfo.platform; // 覆盖为实际平台（'h5'、'mp-weixin'等）
  console.log("平台:"+platform)
} catch (error) {
  console.error('获取平台信息失败：', error);
}

// 基础URL配置
const baseURL = process.env.NODE_ENV === 'development' 
  ? (platform === 'h5'||platform ==='android'|| platform ==='windows'? '/api' : 'http://192.168.1.41:7071') 
  : 'http://192.168.1.41:7071';

// 工具函数：将params对象转为查询字符串
function parseParamsToQuery(params) {
  if (!params || typeof params !== 'object' || Object.keys(params).length === 0) {
    return '';
  }
  const queryStr = Object.entries(params)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&');
  return queryStr ? `?${queryStr}` : '';
}

// 创建axios实例并配置适配器
const http = axios.create({
  baseURL: baseURL,
  timeout: 10000,
  // 非H5环境使用uni.request适配器
  ...(platform !== 'h5' && {
    adapter: function(config) {
      return new Promise((resolve, reject) => {
        // 拼接基础URL和路径
        let finalUrl = config.baseURL + config.url;
        
        // 处理GET请求的参数拼接
        if (config.method.toUpperCase() === 'GET' && config.params) {
          const queryStr = parseParamsToQuery(config.params);
          finalUrl += queryStr;
        }
        
        // console.log("请求路径:", finalUrl);//测试
        
        uni.request({
          url: finalUrl,
          method: config.method.toUpperCase(),
          data: config.data,
          header: config.headers,
          success: (response) => {
            resolve({
              data: response.data,
              status: response.statusCode,
              statusText: response.errMsg,
              headers: response.header,
              config: config
            });
          },
          fail: (error) => {
            reject(new Error(`请求失败：${error.errMsg}`));
          }
        });
      });
    }
  })
});

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    const token = uni.getStorageSync('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
http.interceptors.response.use(
  (response) => {
	  if(response.data.code == 401){
		  uni.removeStorageSync('token');
	  }
    return response.data;
  },
  (error) => {
    const errorMsg = error.message || '网络请求失败，请稍后重试';
    uni.showToast({
      title: errorMsg,
      icon: 'none',
      duration: 3000
    });
    return Promise.reject(error);
  }
);

export default http;